//
//  ConstellationController.m
//  MINFOBBS
//
//  Created by juvid on 13-11-26.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "ConstellationController.h"
#import "MainSearchViewController.h"
#import "UIColor+expanded.h"
#import "DetectionSystemVersion.h"
#import "SBJson.h"
@interface ConstellationController (){
    int theCount,otherCount;
    UIView *vieBtn;
}

@end

@implementation ConstellationController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    self.table.separatorStyle=UITableViewCellSeparatorStyleNone;
    if (self.isPairing) {
        [self BackButton];
        self.table.showsVerticalScrollIndicator=YES;
        self.table.bounces=YES;
         [self SetCellHight:[[[self.arrReturn objectAtIndex:theCount] objectForKey:@"Properties"] objectForKey:@"Property"]];
    }
    else{
    if (self.isSelf) {
        [self SetCellHight:[[[self.arrReturn objectAtIndex:theCount] objectForKey:@"Properties"] objectForKey:@"Property"]];
    }
    else{
        [self BackButton];
        self.table.showsVerticalScrollIndicator=YES;
        self.table.bounces=YES;
        [self GetAllUrl];
        self.table.frame=CGRectMake(12, self.table.frame.origin.y+50, 296, self.table.frame.size.height-65);
        [self BtnOption];
//        [self GetDatas];
    }
    }
    // Do any additional setup after loading the view from its nib.
}
- (void)viewWillDisappear:(BOOL)animated{
    [tRequest clearDelegatesAndCancel];
    [tRequest cancel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [NSThread cancelPreviousPerformRequestsWithTarget:self];
}
-(void)viewDidAppear:(BOOL)animated{
//    if (!self.isSelf) {
//        self.table.hidden=NO;
//        self.table.frame=CGRectMake(12, self.table.frame.origin.y+50, 296, self.table.frame.size.height-50);
//        NSLog(@"%f",self.table.frame.origin.y);
//    }
}
-(void)GetAllUrl{
    if (self.isSingle) {
        [self GetDatas:self.strUrl];
    }
    else{
        NSString *str=[[self.arrReturn objectAtIndex:0] objectForKey:@"Title"];
        
         NSRange rang = [str rangeOfString:@"每周运势"];
        if (rang.location==NSNotFound) {
            
        }
        else{
            
        }
        if ([str hasSuffix:@"每周运势"]) {
//            NSLog(@"%@",str);
            otherCount=2;
        }
        else if([str hasSuffix:@"每日运势"]){
            otherCount=0;
        }
        else if([str hasSuffix:@"年运势"]){
            otherCount=4;
        }
        else if([str hasSuffix:@"每月运势"]){
            otherCount=3;
        }
        else if([str hasSuffix:@"明日运势"]){
            otherCount=1;
        }
        arrAll=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
        [arrAll setObject:[self.arrReturn objectAtIndex:0] atIndexedSubscript:otherCount];
//        [self.arrReturn addObject:@"2"];
//        [self.arrReturn addObject:@"3"];
//        [self.arrReturn addObject:@"4"];
//        [self.arrReturn addObject:@"5"];
//        [self.arrReturn setObject:[self.arrReturn objectAtIndex:0] atIndexedSubscript:theCount];
        
        [self SetCellHight:[[[arrAll objectAtIndex:otherCount] objectForKey:@"Properties"] objectForKey:@"Property"]];
        arrUrl=[[NSMutableArray alloc]init];
        NSArray *arr=[[[arrAll objectAtIndex:otherCount] objectForKey:@"Links"] objectForKey:@"Link"];
        for (int i=0; i<arr.count; i++) {
            NSString *str=[[arr objectAtIndex:i]objectForKey:@"href"];
            NSRange range = [str rangeOfString:@"query="];
            [arrUrl addObject:[str substringFromIndex:range.location +
                               range.length]];
            str=nil;
        }
        arr=Nil;

    }
    //    NSLog(@"%@",arrUrl);
}
-(void)BtnOption{
    int headHight=0;
    NSArray *arr=[[NSArray alloc]initWithObjects:@"今日",@"明日",@"本周",@"本月",@"年度", nil];
    if ([[DetectionSystemVersion alloc]Version]) {
        headHight=64;
    }
    vieBtn=[[UIView alloc]initWithFrame:CGRectMake(12, headHight, 296, 50)];
    vieBtn.backgroundColor=[UIColor whiteColor];
    [self.view insertSubview:vieBtn aboveSubview:self.table];
    for (int i=0; i<5; i++) {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(59*i, 24, 58, 26)];
        [btn setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(PressNextCons:) forControlEvents:UIControlEventTouchUpInside];
        if (i==otherCount) {
            [btn setBackgroundImage:[UIImage imageNamed:@"constellOption"] forState:UIControlStateNormal];

        }
        else{
            [btn setBackgroundImage:[UIImage imageNamed:@"constellOptionUn"] forState:UIControlStateNormal];

        }
                [vieBtn addSubview:btn];
    }
}
//获取其他运势
-(void)PressNextCons:(UIButton *)button{
    for (UIView *subvie in vieBtn.subviews) {
        if ([subvie isKindOfClass:[UIButton class]]) {
            UIButton *btn=(UIButton *)subvie;
            [btn setBackgroundImage:[UIImage imageNamed:@"constellOptionUn"] forState:UIControlStateNormal];
        }
    }
    if ([button.currentTitle isEqual:@"今日"]) {
        theCount=0;
        
    }
    else if([button.currentTitle isEqual:@"明日"]){
        theCount=1;
    }
    else if([button.currentTitle isEqual:@"本周"]){
        theCount=2;
           }
    else if([button.currentTitle isEqual:@"本月"]){
        theCount=3;
        
    }
    else if([button.currentTitle isEqual:@"年度"]){
        theCount=4;
            }
//    NSLog(@"%d  %d",theCount,otherCount);
    if ([[arrAll objectAtIndex:theCount]isKindOfClass:[NSString class]]) {
    
        if (theCount>otherCount) {
            theCount=theCount-1;
        }
        [self GetDatas:[arrUrl objectAtIndex:theCount]];
    }
    else{
        [self SetCellHight:[[[arrAll objectAtIndex:theCount] objectForKey:@"Properties"] objectForKey:@"Property"]];
    }
[button setBackgroundImage:[UIImage imageNamed:@"constellOption"] forState:UIControlStateNormal];
    
}
-(void)SetCellHight:(NSArray *)arrN{
    CGSize sizeFrame;
    arrRowHight=[[NSMutableArray alloc]init];
//    for (int i=0; i<self.arrReturn.count; i++) {
    NSArray *arr=arrN;
    arrRowContent=[[NSMutableArray alloc]init];
    int rowCount=0;
    int start=0;
        if (self.isSelf) {
            if (arr.count>6) {
                rowCount=6;
            }
            start=1;
        }
        else{
            rowCount=arr.count;
        }
        for (int j=start; j<rowCount; j++) {
            NSString *str;
            if (j==0) {
                str=[NSString stringWithFormat:@"%@",[[arr objectAtIndex:j] objectForKey:@"text"]];
            }
            else{
                 str=[NSString stringWithFormat:@"%@:  %@",[[arr objectAtIndex:j] objectForKey:@"name"],[[arr objectAtIndex:j] objectForKey:@"text"]];
            }
            if (str.length!=0) {
                sizeFrame =[str sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(280, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
                [arrRowContent addObject:str];
                [arrRowHight addObject:[NSString stringWithFormat:@"%f",sizeFrame.height]];
            }
        }
          [self.table reloadData];
}


-(void)BackButton{
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 异步数据请求
-(void)GetDatas:(NSString *)strUrl{
    tRequest=[[[ScreenAccess alloc]init]ASIGetSearch:strUrl Start:0 Limit:4];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"allMessage"];
    
}
-(void)requestFinished:(ASIHTTPRequest*)request{
    
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"allMessage"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            if (self.arrReturn==nil) {
                self.arrReturn=[[NSMutableArray alloc]init];
            }
            if (self.isSingle) {
                self.isSingle=NO;
                [ self.arrReturn addObject:[[[[[[[Result objectForKey:@"Response"] objectForKey:@"Categories"] objectForKey:@"Category"] objectAtIndex:0]objectForKey:@"Items"] objectForKey:@"Item"] objectAtIndex:0]];
                [self GetAllUrl];
            }
            else{
            [arrAll setObject:[[[[[[[Result objectForKey:@"Response"] objectForKey:@"Categories"] objectForKey:@"Category"] objectAtIndex:0]objectForKey:@"Items"] objectForKey:@"Item"] objectAtIndex:0] atIndexedSubscript:theCount];
            [self SetCellHight:[[[arrAll objectAtIndex:theCount] objectForKey:@"Properties"] objectForKey:@"Property"]];
            }
        }
    }
    else if([request.username isEqual:@"weather"]){
    }
    
    
}

-(void)requestFailed:(ASIHTTPRequest*)request{
  
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
//    NSLog(@"%d",arrRowContent.count);
    return arrRowContent.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"custont";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.textLabel.text=[arrRowContent objectAtIndex:indexPath.row];
    cell.textLabel.font=[UIFont systemFontOfSize:14];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.textColor=[UIColor colorWithHexString:@"0x4a4a4a"];
//    cell.textLabel.
//     NSLog(@"%f",cell.textLabel.frame.size.width);
    //    NSLog(@"<#string#>")
    // Configure the cell...
    
    return cell;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    float rowHight = 0.0;
    if (arrRowHight.count>0) {
        rowHight=[[arrRowHight objectAtIndex:indexPath.row] floatValue];
    }
    return rowHight+4;
    
}
-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (self.isSelf) {
//        return 5;
//        
//    }
    return 5;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *result;
        result=[[UIView alloc]init];
        result.backgroundColor=[UIColor clearColor];
        
//    }
    return result;
}

-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 38;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result;
    result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    if (self.isSelf) {
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 5, self.table.frame.size.width, 3)];
        img.image=[UIImage imageNamed:@"footLine"];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 3, self.table.frame.size.width, 35)];
        [btn setTitle:@"点击查看全部" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(PrseeMore) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor colorWithHexString:@"0xb7b7b7"] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        [result addSubview:btn];
        [result addSubview:img];
    }
    return result;
}
- (MainSearchViewController *)menuContainerViewController {
    return (MainSearchViewController *)self.parentViewController;
}
-(void)PrseeMore{
    //    if (self.isSelf) {
    ConstellationController *jokecon=[[ConstellationController alloc]init];
    jokecon.arrReturn=self.arrReturn;
    [ [self menuContainerViewController].navigationController  pushViewController:jokecon animated:YES];
    //    }
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
